<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Demo</title>
  <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
  <link href="//unpkg.com/layui@2.9.10/dist/css/layui.css" rel="stylesheet">
  <style>
  ::-webkit-scrollbar {  
		    display: none;  
		}  

    .container {  
    display: flex;  
    justify-content: space-between;  
    padding: 10px;  
}  
  
.left-col, .right-col {  
    padding: 10px;  
}  
  
.specs-settings {  
    display: flex;  
    align-items: center;  
    margin-bottom: 10px;  
}  
  
.specs-actions {  
    margin-left: 10px;  
}  
  
.tree-container {  
    margin-top: 10px;  
}  

.btnstyle{
            width:100px;
            height: 30px;
}

#MySpecs{
    background-image:url('../images/MySpecs_02.gif');
    background-position: 60% 40%;
    background-repeat: no-repeat; /* 背景图片不重复 */  
    /* 调整背景图片大小以覆盖整个元素 */  
    
    /* 其他样式 */  
    margin:0;  
    padding:0;
  }

/* 其他样式... */
</style>
</head>
<body>
  
<div id="specedit" class="layui-form layuimini-form" style="display: none;" >
  <div class="layui-form-item" style="width: 350px;margin-top: 10px;">
    <label class="layui-form-label required">规格ID</label>
    <div class="layui-input-block" >
        <input  type="text"  name="specId" id="spec" readonly  lay-verify="required"   value="" class="layui-input ">
    </div>
</div>


<div id="app">
    <div class="layui-card">
        <div class="layui-card-header" style="margin-left:70px;">
            <h2>规格图片</h2>
        </div>
        <div class="layui-card-body">
            <div class="layui-upload" style="margin-left:70px;">
                <img id="pic" src="../images/combo_02.webp" style="width:100px;height:60px" alt="">
                <button type="button" class="layui-btn" id="browser-pic" style="margin-left:35px">
                    <i class="layui-icon">&#xe67c;</i>浏览图片
                </button>

            </div>
        </div>
    </div>
</div>  

<div class="layui-form-item" style="margin-top:20px;margin-left: 50px;">
    <div class="layui-input-block" >
        <button  class="layui-btn layui-btn-normal" id="btn_ok" lay-submit lay-filter="saveSpecs">确认保存</button>
    </div>
</div>
</div>  

  <div id="Styepadddiv" style="display:none;margin-left:-35px" class="layui-card">
    <form class="layui-form" action="">
        <div class="layui-card-body">
            <div class="layui-row">
                <div class="layui-form-item">
                    <label class="layui-form-label required">规格类型</label>
                    <div class="layui-input-block">
                        <input type="text" name="Stype" lay-verify="required" lay-reqtext="类型名不能为空" placeholder="请输入规格类型" value="" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-row">
              <div class="layui-form-item">
                  <label class="layui-form-label required">是否多选</label>
                  <div class="layui-input-block">
                    <select  name="Stypecount" lay-verify="">
                      <option value="">--是否多选--</option>
                      <option value="0">单选</option>
                      <option value="1">多选</option>
                    </select>
                  </div>
              </div>
          </div>

            <div class="layui-row" style="height:50px;">
                <div class="layui-form-item" style="margin-top: 20px;padding-right:50px">
                    <div class="layui-input-block" style="margin-left:125px">
                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!--规格类型添加-->


<div class="layui-row container" style="background-color: #99CC99;">  
    <div class="layui-col-xs4 left-col" id="MySpecs">  
        <div class="specs-settings"  style="margin-top: 12px;">  
            <h2 style="color: #fff; padding-left:10px;padding-top: 10px;">规格设置</h2>  

            <div id="btntype" class="specs-actions">  
                <img  class="add-specs-btn" style="padding-top: 10px; width:40px; height: 50px; cursor: pointer;" src="../images/ChildrenSpecs .png">  
            </div> 
        </div>  
        <div id="ID-tree-demo-showLine" class="tree-container" style="margin-left: 7.5px; width: 350px; border: 1px solid #ccc; background-color: #99CC99;"></div>  
    </div>  

    <div class="layui-col-xs7">  
        <fieldset class="table-search-fieldset"   style="border: 1px solid #ccc;">  
            <legend>搜索信息</legend>  

                <div class="layui-form-item">  
                    <div class="layui-inline" style="margin-left: 15px;">  
                        <label class="layui-form-label">规格ID查询</label>  
                        <div class="layui-input-inline">  
                            <input type="text" name="username" autocomplete="off" class="layui-input">  
                        </div>  
                    </div>  
                    <div class="layui-inline">  
                        <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>  
                    </div>  

                    <div style="padding: 16px;" >
                        <table class="layui-hide" style="border: 1px solid #99CC99;"  id="test" lay-filter="test"></table>
                    </div>
                    
                    <script type="text/html" id="barDemo">
                        <div class="layui-clear-space">
                          <a class="layui-btn layui-btn-xs" lay-event="edit"><img src="../images/修改 (1).png"  style="width: 24px;margin-left: -1px;margin-top: -3px;"></a>
                          <a class="layui-btn layui-btn-xs" lay-event="delete"><img src="../images/删除 (2).png"  style="width: 24px;margin-left: -1px;margin-top: -3px;"></a>
                        </div>
                    </script>

                </div>  
        </fieldset>  
    </div>  
</div>  
    
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn btnstyle" lay-event="add"  style="background-color: #33CC99;"><img src="../images/规格参数.png" alt="" style="width: 24px;margin-left: -5px;">规格添加 </button>         
  </div>
</script>


<script src="//unpkg.com/layui@2.9.10/dist/layui.js"></script>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script>    
  var requrl=" http://localhost:8080/restaurant_web_war_exploded/";
  var treedata; 
  var treedatalength;
  var specs=[];
  var addspecs=[];

function ParentSpec(speid, spname) {
this.id = speid;
this.title = spname;
}

  
 layui.use(['form', 'table','tree','upload'], function () {
        var $ = layui.jquery,
            form = layui.form,
            layer = layui.layer,
            tree=layui.tree,
            upload=layui.upload,
            table = layui.table;

  var myfile;
  //第三：使用组件
  let uploadInst = upload.render({
            // 绑定浏览文件元素
            elem: '#browser-pic',
            
            // 设置允许上传的文件类型
            accept: 'file',

            // 设置允许上传的文件后缀
            exts: 'jpg|png|jpeg|gif|webp',

            // 设计允许上传文件的大小，单位：KB
            size: 10 * 1024,
                
            // 设置不自动上传
            auto: false,

            error: function (error) {			//上传失败的回调
                
            },
            choose: function (obj) {		//选择文件后的回调
                obj.preview(function (index, file, result) {
                    myfile=file;                     
                    //显示图片
                    $("#pic").prop("src", result);
                });
            }
        });

  window.addEventListener('message', function(event) {  
  if (event.data =='specssuccess') {  
    table.reload('test');
    var index= layui.layer.load(3, {  
    shade: [1,'#fff']  })//0.1透明度的白色背景 
    setTimeout(function(){
    layer.close(index);  
    layer.msg("规格添加成功!!!",{icon:6,time:1000})
  },1500)  
  }
  }, false);     
  

     function getTreeData (aaa){
          $.ajax({
            url:requrl+"specType/listSpecType",
            data:{"page":1,"limit":100},
            async: false,
            success:function (res){
                 treedata=res.data.list;
                 treedatalength=res.data.list.length;
                 for (let index = 0; index < treedata.length; index++) {
                  aaa.push(new ParentSpec(treedata[index].specTypeId,treedata[index].specTypeName))
                }
            }
        })
      }
      //获取规格类型  

     getTreeData(specs); 

    // 创建渲染实例
  table.render({
      toolbar:'#toolbarDemo',
      elem: '#test',
      url: requrl+"spec/listSpec", // 此处为静态模拟数据，实际使用时需换成真实接口
      totalRow: true, // 开启合计行
      parseData:function(res){
        enSureData=res.data==null?true:false;    
        let list=[{content: "暂无数据，请稍后再试。"}]
        let mydata=res.data==null?list:res.data.list;
        return{
        code: 0, //解析接口状态
        msg: res.message, //解析提示文本
        count: res.data===null?0:res.data.total, //解析数据长度
        data: mydata //解析数据列表
        }
      },
      limits: [ 10, 15, 20],
      limit: 7,
      page: true,
      cols: [[
        {field:'specId',width:225,fixed: 'left', title: 'ID'},
        {field:'specName',width:225, title: '规格名'},
        {fixed: 'right',width:255, title:'操作', toolbar:'#barDemo'}
      ]] 
    });

  //树结构渲染
  tree.render({
    elem: '#ID-tree-demo-showLine',
    data: specs,
    showLine: false,  // 是否开启连接线
    click: function(obj){
        //执行搜索重载
        var index= layui.layer.load(3, {  
        shade: [1,'#fff']  })//0.1透明度的白色背景 

        table.reload('test', {
        where: {specTypeId:obj.data.id},//模糊查询传值
        page: {
             curr: 1,
            }
        });

        setTimeout(function(){
          layer.close(index);
        },1200)
      }
  });
  

    // 触发单元格工具事件(表格右侧按钮)
      table.on('tool(test)', function(obj){ // 双击 toolDouble
      var data = obj.data; // 获得当前行数据
      addspecs=[];
      if(obj.event === 'delete'){
      } else if(obj.event === 'more'){
        // 更多 - 下拉菜单
        dropdown.render({
          elem: this, // 触发事件的 DOM 对象
          show: true, // 外部事件触发即显示
          data: [{
            title: '查看',
            id: 'detail'
          },{
            title: '删除',
            id: 'del'
          }],
          click: function(menudata){
            if(menudata.id === 'detail'){
              layer.msg('查看操作，当前行 ID:'+ data.id);
            } else if(menudata.id === 'del'){
              layer.confirm('真的删除行 [id: '+ data.id +'] 么', function(index){
                obj.del(); // 删除对应行（tr）的DOM结构
                layer.close(index);
                // 向服务端发送删除指令
              });
            }
          },
          align: 'right', // 右对齐弹出
          style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
        })
      } else if(obj.event==="edit"){
         $("#spec").val(obj.data.specId); 
        var index = layer.open({
          title: '修改规格',
          type: 1,
          shade: 0.2,
          maxmin: true,
          shadeClose: true,
          area: ['40%', '55%'],
          content:$("#specedit"), 
          end: function() {    
          $('#specedit').hide(); // 在弹出层关闭时隐藏原始 div  
          }
        })
      }
    });

      
      /**
         * toolbar监听事件
         */
         table.on('toolbar(test)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
              var index = layer.open({
                title: '添加规格',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['70%', '66%'],
                content: '../html/speces_add.html',
              })
            }
        });

          // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            layer.alert(result, {
                title: '最终的搜索信息'
            });

            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    searchParams: result
                }
            }, 'data');

            return false;
        });  

        var index;
        $("#btntype").click(function (){
               index=layer.open({
                title: '类型添加',
                type: 1,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['40%', '52%'],
                content:$('#Styepadddiv'),
              end: function() {  
                $('#Styepadddiv').hide(); // 在弹出层关闭时隐藏原始 div  
              },
            }) 
        })

        //规格类型添加
        form.on('submit(saveBtn)', function (data) {
            addspecs=[];
            var iframeindex= layui.layer.load(3, {  
            shade: [1,'#fff']  })//0.1透明度的白色背景
              
            $.ajax({
                type:"post",
                url:requrl+"specType/insertSpecType",
                data:{specTypeName:data.field.Stype,specTypeCount:data.field.Stypecount},
                success:function (res){
                getTreeData(addspecs);  
                tree.render({
                      elem: '#ID-tree-demo-showLine',
                      data: addspecs,
                      showLine: false,  // 是否开启连接线
                }); 
                
                setTimeout(function(){
                  layer.close(index); // 关闭当前 iframe 弹层  
                },200)
                setTimeout(function(){   
                   layer.close(iframeindex);      
                    // 更新元素          
                },300);   


                layer.msg("添加规格类型成功!",{icon:6,time:350},function (){
                    $("input[name='Stype']").val("");
                }) 
              }
            })
           return false; //阻止表单默认提交
        });


        //规格修改
      form.on('submit(saveSpecs)', function (data) {
        // console.log("speUp............");
            if(myfile===null){
              layer.msg('请选择你要添加的规格图',{icon:5,time:1000,shift:6});
              return false; 
            } 
               // 创建一个 FormData 实例  
            var formData = new FormData();  

            formData.append('specId',data.field.specId);
            formData.append('specFile',myfile);
            $.ajax({
                type:"post",
                url:requrl+"spec/updateSpec",
                data:formData,
                processData: false, // 告诉 jQuery 不要去处理发送的数据 
                contentType: false, // 告诉 jQuery 不要去设置 Content-Type 请求头  
                success:function (res){
                    // console.log(res);
                }
            })
        });
})

</script>
</body>
</html>